//
//  ApplyStoreVC.swift
//  物料商行
//
//  Created by HaoDong Hong on 2017/9/3.
//  Copyright © 2017年 HaoDong Hong. All rights reserved.
//

import UIKit
import SCLAlertView

class ApplyStoreVC: UIViewController {
    
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var applyButton: UIButton!
    @IBOutlet weak var truck: UIImageView!
    
    var alertViewResponder: SCLAlertViewResponder?
    let storyBoard = UIStoryboard(name: "MainStoryboard", bundle: nil)
    let helper = StoreVCHelper()
    var refreshControl: UIRefreshControl!
    
    
    func prepareApplyState() {
        refreshControl.beginRefreshing()
        authenticate()
    }
    
    /// 查看是否拥有商店
    func checkStore() {
        helper.exist { (netWork, exist) in
            self.refreshControl.endRefreshing()
            if netWork {
                if exist! {
                    self.authenticate()
                } else {
                    self.showAlert()
                }
            } else {
                self.showError(message: "网络错误，请重试")
            }
        }
    }
    private func authenticate() {
        helper.authenticate { (success, storeState, reason) in
            if success {
                self.applyButton.isEnabled = true
                switch storeState! {
                case .Failure:
                    if reason != nil {
                        self.applyButton.setTitle("重新申请认证", for: .normal)
                        self.showReason(reason!)
                    } else {
                        self.showAlert()
                    }
                    
                case .Success:
                    self.showSuccess(message: "认证成功")
                    let storyBoard = UIStoryboard(name: "MainStoryboard", bundle: nil)
                    let mainVC = storyBoard.instantiateViewController(withIdentifier: "MainViewController")
                    let nv = UINavigationController(rootViewController: mainVC)
                    self.revealViewController().setFront(nv, animated: true)
                case .Auditting:
                    self.applyButton.isEnabled = false
                    self.applyButton.setTitle("正在处理您的认证信息", for: .normal)
                }
            } else {
                self.showError(message: "网络连接失败，请重试")
                self.applyButton.isEnabled = false
            }
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if self.revealViewController() != nil {
            //self.revealViewController().delegate = self
            view.addGestureRecognizer(revealViewController().panGestureRecognizer())
            view.addGestureRecognizer(revealViewController().tapGestureRecognizer())
            
        }
        scrollView.contentInset = UIEdgeInsetsMake(0.5, 0, 0, 0)
        refreshControl = UIRefreshControl()
        refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
        refreshControl.addTarget(self, action: #selector(refresh(_:)), for: UIControlEvents.valueChanged)
        scrollView.insertSubview(refreshControl, at: 0)
        refreshControl.beginRefreshing()
        checkStore()
        //showAlert()
        // Do any additional setup after loading the view.
    }
    @objc func refresh(_ refreshView: UIRefreshControl) {
        checkStore()
    }
    private func pushCreateStoreVC() {
        let vc = storyBoard.instantiateViewController(withIdentifier: "CreateStoreVC") as! CreateStoreVC
        vc.delegate = self
        self.navigationController?.pushViewController(vc, animated: true)
    }
    @IBAction func applyButtonDidTapped(_ button: UIButton!) {
        pushCreateStoreVC()
    }
    /// MARK: 请求是否确认创建商店
    func showAlert() {
        let apperance = SCLAlertView.SCLAppearance(showCloseButton: false)
        let alertView = SCLAlertView(appearance: apperance)
        alertView.addButton("确认", target: self, selector: #selector(createStoreButtonDidTapped(_:)))
        alertView.addButton("取消", target: self, selector: #selector(cancelAlertView(_:)))
        
        alertViewResponder = alertView.showNotice("温馨提示", subTitle: "需要创建商店后，才能使用物料商行的功能。创建商店后，无法被添加为商店成员。是否确认创建？")
        
    }
    @objc func createStoreButtonDidTapped(_ button: UIButton!) {
        alertViewResponder?.close()
        applyButton.isEnabled = true
        helper.createStore { (success) in
            if success {
                self.pushCreateStoreVC()
            } else {
                self.showError(message: "网络错误，请重试")
            }
        }
    }
    @objc func cancelAlertView(_ button: UIButton!) {
        alertViewResponder?.close()
        applyButton.isEnabled = false
    }
    
    /// MARK: 认证失败，请求是否重新认证
    func showReason(_ reason: String) {
        let apperance = SCLAlertView.SCLAppearance(showCloseButton: false)
        let alertView = SCLAlertView(appearance: apperance)
        alertView.addButton("确认", target: self, selector: #selector(applyButtonTapped(_:)))
        alertView.addButton("取消", target: self, selector: #selector(cancelAlertView(_:)))
        alertViewResponder = alertView.showWarning("认证失败", subTitle: reason)
    }
    @objc func applyButtonTapped(_ button: UIButton!) {
        pushCreateStoreVC()
    }
    
    
}
extension ApplyStoreVC: createStoreDelegate {
    
    func didCreateStore(bool: Bool) {
        if bool {
            applyButton.setTitle("正在处理您的认证信息", for: .normal)
            applyButton.isEnabled = false
        } else {
            applyButton.setTitle("申请认证", for: .normal)
            applyButton.isEnabled = true
        }
    }
}
extension ApplyStoreVC: LoginDelegate {
    func prepareMainVC(state: AppState) {
        switch App.state {
        case .AdminState:
            let storyBoard = UIStoryboard(name: "MainStoryboard", bundle: nil)
            let mainVC = storyBoard.instantiateViewController(withIdentifier: "MainViewController")
            let nv = UINavigationController(rootViewController: mainVC)
            self.revealViewController().setFront(nv, animated: true)
        case .ApplyState:
            let navigationVC = UINavigationController(rootViewController: ApplyStoreVC())
            self.revealViewController().setFront(navigationVC, animated: true)
        case .MemberState:
            let navigationVC = UINavigationController(rootViewController: MemberVC())
            self.revealViewController().setFront(navigationVC, animated: true)
        case .none:
            break
        }
    }
    func loginSuccess(from state: AppState) {
        prepareMainVC(state: state)
    }
}
